package com.engine.cube.cmd.card;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.api.cube.util.CubeUtil;
import com.api.ecme.service.EcmeBaseService;
import com.api.formmode.cache.ModeComInfo;
import com.api.formmode.cache.ModeFormComInfo;
import com.api.formmode.service.ScriptManagerService;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.cube.biz.*;
import com.engine.cube.cmd.app.CubeCrmTagInfo;
import com.engine.cube.entity.CardEntity;
import com.weaver.formmodel.util.StringHelper;

import weaver.archives.util.ArchivesFModeUtil;
import weaver.conn.RecordSet;
import weaver.formmode.setup.ModeSetUtil;
import weaver.formmode.virtualform.VirtualFormHandler;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.systeminfo.SystemEnv;

public class CubeLayoutBaseGet extends AbstractCommonCommand<Map<String, Object>> {
    private CardEntity card;
    public CubeLayoutBaseGet(Map<String, Object> stringObjectMap, User user) {
       this.params = stringObjectMap;
       this.user = user;
    }

    @Override
    public BizLogContext getLogContext() {
        return null;
    }

    @Override
    public Map<String, Object> execute(CommandContext commandContext) {
        Map<String, Object> result = new HashMap<String, Object>();

        String isecme = ParamUtil.get(params,"isecme");
        if("1".equals(isecme)){
        	return new EcmeBaseService().getLayoutBase(params);
        }
        //浏览框不关联模块modeId转换逻辑
        String modeid = ParamUtil.get(params,"modeId");
        String formId = ParamUtil.get(params,"formId");
        String billid = ParamUtil.get(params,"billid");
        String customid = ParamUtil.get(params,"customid");
        String isPreview = ParamUtil.get(params,"isPreview");
        String formmodeid = "";
        RecordSet rs=new RecordSet();
        if((StringHelper.isEmpty(modeid)||modeid.equals("0"))&&!StringHelper.isEmpty(formId)&&!StringHelper.isEmpty(billid)){
            rs.execute("select tablename from workflow_bill where id="+formId);
            if(rs.next()){
                String tablename=rs.getString("tablename");
                if(VirtualFormHandler.isVirtualForm(formId)){
                    tablename = VirtualFormHandler.getRealFromName(tablename);
                }
                rs.execute("select formmodeid from "+tablename+" where id="+billid);
                if(rs.next()){
                    formmodeid=rs.getString("formmodeid");
                    params.replace("modeId",formmodeid);
                }
            }
        }

        this.card = CardHelper.initCardEntity(params);
        if(!"1".equals(isPreview)){
            CardHelper.checkRight(card, user);
            // 增加档案方权限判断，与建模权限取最高权限
            Map<String, Boolean> archiveRight = ArchivesFModeUtil.checkAndGetArchiveRight(modeid, formId, billid, user);
            if(!archiveRight.getOrDefault("hasRight", false) &&(!card.isRight() || (card.getType() == 2 && !card.isEdit()))){
                result.put("noRight", true);
                return result;
            }
        }
        if(VirtualFormHandler.isVirtualForm(formId) && "0".equals(modeid)){//QC682826
            RecordSet rs1=new RecordSet();
            String virtualformtype = "";//虚拟表类型 1、"":SQL语句 2、"0":虚拟表单 3、"1":视图
            rs1.executeQuery("select virtualformtype from modeformextend where formid=?",formId);
            while(rs1.next()){
                virtualformtype = rs1.getString("virtualformtype");
            }
            rs1.executeQuery("select modeid from mode_customsearch where formid=? and id=? ",formId,customid);
            String modeId = "";//查询列表关联模块id
            while (rs1.next()){
                modeId = Util.null2String(rs1.getString("modeid"));
            }
            if(("".equals(virtualformtype) || "1".equals(virtualformtype)) && ("".equals(modeId) || "0".equals(modeId))) {//视图或SQL查询列表未关联模块
                result.put("errorPage", true);
                result.put("message", SystemEnv.getHtmlLabelName(510988, user.getLanguage()));//未选择关联模块
                return result;
            }
        }
        CardHelper.getResolveFormMode(card, user);
        int _layoutid = card.getLayoutId();
        if(_layoutid<=0) {
            result.put("errorPage", true);
            result.put("message",SystemEnv.getHtmlLabelName(384317, user.getLanguage()));//未找到对应模板
            return result;
        }
        if(card.getVersion()!=2) {
            result.put("layoutType","1");
            return result;
        }

        int editlayoutid=0;
        if (card.isIsquickedit()) {//显示布局并且开启快速编辑
        	editlayoutid=CardHelper.getEditLayoutidForView(card, user);
        	result.put("editLayoutid", editlayoutid);
        	addQuickeditValue(result,commandContext,card);
        }
        String tableName="";
        try {//正式系统 商机卡片  查看日志记录
            ModeFormComInfo modeFormComInfo = new ModeFormComInfo();
            tableName = modeFormComInfo.getTableName(card.getFormId());
            if(card.getType() ==0&&card.getModeId()!=0&&"true".equals(CubeUtil.getIsFormal())&&"CRM_SellChance".equals(tableName)){//来自正式系统 且是商机表
                String currentdate = TimeUtil.getCurrentDateString();
                String currenttime = TimeUtil.getOnlyCurrentTimeString();
                rs.executeSql("insert into CRM_SellChanceLog (sellchanceid,type,operator,operatedate,operatetime,operatefield,oldvalue,newvalue)"
                        +" values("+card.getBillId()+",0,"+user.getUID()+",'"+currentdate+"','"+currenttime+"','','','')");
            }
        } catch (Exception e) {
            e.printStackTrace();
            writeLog(e);
        }
        Map<String,Object> map=CardFormHelper.getLayoutFields(_layoutid, card.isIsquickedit(), editlayoutid);
        int modedatastatus =card.getModedatastatus();//数据状态 0正式 1草稿 默认0
        //判断密级字段如果是密级的，保存为草稿后，密级可修改，保存为正式数据后，密级不可再修改。
        result.put("fields", map);
        //非正式系统  正式系统除商机表外记录查看日志
        if("false".equals(CubeUtil.getIsFormal())||("true".equals(CubeUtil.getIsFormal())&&!"CRM_SellChance".equals(tableName))){
            new CardHelper().recordLog(card, user);
        }
        result.put("layoutid", _layoutid);
        result.put("isquickedit", card.isIsquickedit()?"1":"0");
        int cardtype = card.getType();
        if(cardtype == 0){
        	rs.executeQuery("select dsdesignerid from modehtmllayout where modeid=? and type=4 and isdefault=1", modeid);
        	if(rs.next()){
        		if(!Util.null2String(rs.getString("dsdesignerid")).equals("")){
            		String printEdcUrl = "/spa/edc/static4engine/report/engine.html#/edcreportengine/sheetView?id="+Util.null2String(rs.getString("dsdesignerid"));
            		result.put("printEdcUrl", printEdcUrl);
            	}
        	}
        		
        }
        result.put("secondPassword", card.getSecondPassword());
        rs.execute("select detailPageSize from formEngineSet");
        String detailPageSize = "10";
        if(rs.next()){
            detailPageSize = rs.getString("detailPageSize");
        }
        result.put("detailPageSize", detailPageSize);
        JSONObject datajson = JSONObject.parseObject(card.getDatajson());

        JSONObject etablesJsonArray = datajson.getJSONObject("eformdesign").getJSONObject("etables");
        Set<String> keys = etablesJsonArray.keySet();
        Set<String> detailKeys = keys.stream().filter(key -> key.contains("detail_")).collect(Collectors.toSet());
        for (String detailKey : detailKeys) {
            JSONObject jobject = datajson.getJSONObject("eformdesign").getJSONObject("etables").getJSONObject(detailKey);
            if (jobject == null){
                continue;
            }
            JSONArray jsonArray = jobject.getJSONArray("ec");
            if (jsonArray == null){
                continue;
            }
            JSONArray array = new JSONArray();
            for (int j = 0; j < jsonArray.size() ; j++) {
                JSONObject jsonObject = jsonArray.getJSONObject(j);
                int etype = jsonObject.getIntValue("etype");
                String value = jsonObject.getString("evalue");
                if (etype == 1){
                    String evalue = "";
                    if ("序号".equals(value)){
                        evalue =  SystemEnv.getHtmlLabelName(528219, user.getLanguage());
                    }else if("合计".equals(value)){
                        evalue =  SystemEnv.getHtmlLabelName(530636, user.getLanguage());
                    }

                    if (evalue == "" || evalue ==null){
                        evalue = jsonObject.getString("evalue");

                    }
                    jsonObject.put("evalue",evalue);
                }
                array.add(jsonObject);
            }
            datajson.getJSONObject("eformdesign").getJSONObject("etables").getJSONObject(detailKey).remove("ec");
            datajson.getJSONObject("eformdesign").getJSONObject("etables").getJSONObject(detailKey).put("ec",array);
        }        
        
        String script = new ScriptManagerService().getLayoutScriptStr(_layoutid);

        String custompage = "";
        List<String> jspPage= new ArrayList();
        rs.executeQuery("select custompage from modeinfo where id=? and iscustompage =1", modeid);
        if(rs.next()){
            custompage = Util.null2String(rs.getString("custompage")).trim();
        }
        if(!"".equals(custompage)){
            jspPage.add(custompage);
        }
        CustomPageRangeCache.appendPage(jspPage);
        ParseLayout layout = new ParseLayout();
        try {
			layout.parseLayoutJson(datajson);
		} catch (Exception e) {
			writeLog("卡片后台布局解析出错...");
			writeLog(e);
		}
        int  detailnum =0;
        //获取固定列(主表--》明细表--》明细表设置)
        ModeComInfo comInfo = new ModeComInfo();
        String sql = "select * from Workflow_billdetailtable a left join modeformgroup b on a.billid=b.formid and b.layoutid="+_layoutid+" and b.modeid="+card.getModeId()+" and ";
        if("ORACLE".equalsIgnoreCase(rs.getDBType())){
            sql += " TO_NUMBER(a.orderid-1) = b.groupid";
            sql += " where a.billid="+formId+"  order by TO_NUMBER(a.orderid-1)";
        }else if("mysql".equalsIgnoreCase(rs.getDBType())){
            sql += " cast(a.orderid-1 as signed) = b.groupid ";
            sql += " where a.billid="+formId+"  order by cast(a.orderid-1 as signed) ";
        }
         else if("postgresql".equalsIgnoreCase(rs.getDBType())){
            sql += " TO_NUMBER(a.orderid-1) = b.groupid";
            sql += " where a.billid="+formId+"  order by TO_NUMBER(a.orderid-1)";
        }
        else{
            sql += " convert(int, a.orderid-1) = b.groupid";
            sql += " where a.billid="+formId+"  order by  convert(int, a.orderid-1)";
        }
        rs.executeSql(sql);
      //  rs.executeQuery("select * from Workflow_billdetailtable a left join modeformgroup b on a.billid=b.formid and b.layoutid=? and  convert(int, a.orderid-1) = b.groupid where a.billid=? order by a.orderid asc",_layoutid,formId);
        List<String> fixFieldStrs = new ArrayList<String>();
        JSONObject detailMergeTypeJson = new JSONObject();
        JSONObject detailOpenCustomOrder = new JSONObject();
        boolean hasmergetype = false;
        while(rs.next()){
            detailnum++;
            boolean isDragula = false;
            String tablename=rs.getString("tablename");
            boolean isNeedPagination = false;
            boolean openCustomOrder = comInfo.isOpenCustomOrder(card.getModeId()+"", tablename);
            int isPagination =Util.getIntValue(rs.getString("isPagination"),0);//分页
            int type = Util.getIntValue(rs.getString("type"),0);
            if(isPagination==1&&(type==0||type==1||type==2)){
                isNeedPagination = true;
            }
            if((type==1||type==2)&&openCustomOrder&&!isNeedPagination){
                isDragula = true;
            }
            String detailindex = Util.null2String(rs.getString("orderid"));
            detailOpenCustomOrder.put("detail_"+detailindex,isDragula);
            String fixField = rs.getString("fixfield");
            if(null != fixField && !"".equals(fixField)) fixFieldStrs.add(fixField);
            if(!"0".equals(rs.getString("mergetype"))){
                detailMergeTypeJson.put(detailindex,rs.getString("mergetype"));
                hasmergetype = true;
            }
        }
        result.put("detailOpenCustomOrder", detailOpenCustomOrder);
        //如果有固定列设置，对dataJson 进行解析
        if(fixFieldStrs.size() > 0 || hasmergetype){
            JSONObject eformdesignJson = datajson.getJSONObject("eformdesign");
            JSONObject etablesJson = eformdesignJson.getJSONObject("etables");

            for (int detailIndex = 1; detailIndex <= detailnum; detailIndex++) {
                JSONObject detailJson = etablesJson.getJSONObject("detail_"+detailIndex);
                if(null == detailJson) continue;
                //存储合并行类型
                detailJson.put("mergeType",detailMergeTypeJson.get(""+detailIndex));

                //将合并行的数据返回给前端。
             //   rs.executeQuery("select * from Workflow_billdetailtable a left join modeformgroup b on a.billid=b.formid and b.layoutid=? and  convert(int, a.orderid-1) = b.groupid where a.billid=?  and  orderid =? order by a.orderid asc",_layoutid,formId,detailIndex);
                String sql1= "select * from Workflow_billdetailtable a left join modeformgroup b on a.billid=b.formid and b.layoutid="+_layoutid+" and b.modeid="+card.getModeId()+"  and " ;
                if("ORACLE".equalsIgnoreCase(rs.getDBType())){
                    sql1 += " TO_NUMBER(a.orderid-1) = b.groupid";
                    sql1 += " where a.billid="+formId+" and orderid="+detailIndex+" order by TO_NUMBER(a.orderid-1)";
                }else if("mysql".equalsIgnoreCase(rs.getDBType())){
                    sql1 += " cast(a.orderid-1 as signed) = b.groupid ";
                    sql1 += " where a.billid="+formId+" and orderid="+detailIndex+" order by cast(a.orderid-1 as signed) ";
                }
                else if("postgresql".equalsIgnoreCase(rs.getDBType())){
                    sql1 += " TO_NUMBER(a.orderid-1) = b.groupid";
                    sql1 += " where a.billid="+formId+" and orderid="+detailIndex+" order by TO_NUMBER(a.orderid-1)";
                }
                else{
                    sql1 += " convert(int, a.orderid-1) = b.groupid";
                    sql1 += " where a.billid="+formId+" and orderid="+detailIndex+" order by  convert(int, a.orderid-1)";
                }
                rs.executeSql(sql1);
                String  mergeField="";
                while(rs.next()){
                    mergeField=Util.null2String(rs.getString("mergeFields"));
                }

                String [] mergeFields  = mergeField.split(",");

//                //如果没有固定列设置，则不需要进行后续逻辑
//                if(fixFieldStrs.size() == 0) continue;
                //获取ec集合内容
                JSONArray ecArrays = detailJson.getJSONArray("ec");
                //存储合并行的列id以及下标索引（需要按排序存储）
                JSONObject mergeFieldJsons = new JSONObject();
                int mergefildCounts = 0;
                for(int i = 0;i < ecArrays.size();i++){
                    JSONObject jsonObject = ecArrays.getJSONObject(i);
                    //获取列固定的下标索引
                    if(null != jsonObject && fixFieldStrs.contains(jsonObject.getString("field"))){
                        //解析id，获取逗号后面的数字
                        String idStr = jsonObject.getString("id");
                        String[] split = idStr.split("\\,");
                        //存储固定列字段
                        detailJson.put("fixFieldIndex",split[1]);
                    }

                    for(int j = 0; j < mergeFields.length;j++){
                        if(mergeFieldJsons.get(j+"") != null) continue;
                        if(null != jsonObject && mergeFields[j].equals(jsonObject.getString("field"))){
                            JSONObject mergeFieldJson = new JSONObject();
                            mergeFieldJson.put("fieldid",mergeFields[j]);
                            //解析id，获取逗号后面的数字
                            String idStr = jsonObject.getString("id");
                            String[] split = idStr.split("\\,");
                            mergeFieldJson.put("fieldIndex",split[1]);
                            mergeFieldJsons.put(j+"",mergeFieldJson);
                            mergefildCounts++;
                        }
                    }
                }
                mergeFieldJsons.put("count",mergefildCounts);
                detailJson.put("mergeFields",mergeFieldJsons);
            }
        }
        //查询当前数据状态。

        result.put("script",LayoutHelper.splitScript(script));
        result.put("custompage",custompage);
        result.put("datajson",datajson);
        if(null != this.card){
            result.put("datastatus",card.getModedatastatus());// 0:正式 1：草稿
        }else{
            result.put("datastatus","0");
        }

        return result;
    }

    /**
     * 添加显示页面快速编辑返回值
     * @param result
     * @param card2
     */
	private void addQuickeditValue(Map<String, Object> result,CommandContext commandContext,CardEntity card) {
		//pageexpandid
		RecordSet rs = new RecordSet();
		ModeSetUtil setUtil = new ModeSetUtil();
		int modedatastatus = setUtil.getModedatastatusValue(rs, card.getModeId(),Util.getIntValue( card.getBillId()));
		int pageexpandid=0;
		String sql="select id from mode_pageexpand where modeid=? and issystemflag=2 and issystem=1 ";
		if (modedatastatus==1) {//草稿要执行的接口
			sql="select id from mode_pageexpand where modeid=? and issystemflag=13 and issystem=1 ";
		}
		rs.executeQuery(sql, card.getModeId());
		if (rs.next()) {
			pageexpandid=rs.getInt("id");
		}
		result.put("pageexpandid", pageexpandid);
		String haveInterface="0";
		if (pageexpandid>0) {
			sql="select id from mode_actionview where expandid=? and actiontype!='0' union all "
					+"select a.id from mode_pageexpanddetail a left join mode_timedtask_detail b on a .taskdetailid = b. id  where mainid =? and (a.isenable = 1 or b.isenable=1)";
			rs.executeQuery(sql, pageexpandid,pageexpandid);
			if (rs.next()) {
				haveInterface="1";
			}
		}
		result.put("haveInterface", haveInterface);
		VerifyEntityGet verifyEntity = new VerifyEntityGet(this.params, user);
		Map<String, Object> execute = verifyEntity.execute(commandContext);
		@SuppressWarnings("unchecked")
		Set<String> fields = (Set<String>) execute.get("fields");
		JSONArray fieldinfos = (JSONArray) execute.get("fieldinfos");
		result.put("verify_fields", fields);
		result.put("verify_fieldinfos", fieldinfos);
		result.put("haveVerifyRepeat", fields.size()>0?"1":"0");
		Set<String> relateField = new HashSet<String>();
		//tab页中设置关联字段返回
		sql="select w.id from mode_pagerelatefielddetail d left join workflow_billfield w on w.fieldname=d.modefieldname and w.viewtype=0 and w.billid=?  where mainid in (select id from mode_pagerelatefield where pageexpandid in (select id from mode_pageexpand where modeid=? and issystem=0 and isshow=1))";
		rs.executeQuery(sql, card.getFormId(),card.getModeId());
		while (rs.next()) {
			String id=Util.null2String(rs.getString("id"));
			if (!"".equals(id)) {
				relateField.add("field"+id);
			}
		}
		result.put("relateField", relateField);
	}

}